package com.lcx.plugin.ui;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.intellij.openapi.fileChooser.FileChooser;
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.VirtualFile;
import com.lcx.plugin.constants.StrConstant;
import com.lcx.plugin.dict.GlobalDict;
import com.lcx.plugin.service.impl.ExcelAnalysisServiceImpl;
import com.lcx.plugin.tool.CacheDataUtils;
import com.lcx.plugin.tool.ProjectUtils;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author daxiong
 * @date 2023/6/13 下午4:44
 */
public class SelectFile extends DialogWrapper {

    /**
     * 主面板
     */
    private JPanel contentPane;
    /**
     * 路径字段
     */
    private JTextField pathField;
    /**
     * 路径选择按钮
     */
    private JButton pathChooseButton;
    /**
     * 表存在跳过复选框
     */
    private JCheckBox tableExistJumpCheckBox;
    private JLabel selectFileLabel;
    private JButton downloadTemplateButton;
    private JTextField downloadTemplateField;
    private JLabel downloadLabel;
    private JButton chooseDownloadButton;
    /**
     * 数据缓存工具类
     */
    private final CacheDataUtils cacheDataUtils = CacheDataUtils.getInstance();
    /**
     * 项目对象
     */
    private final Project project;

    /**
     * 构造方法
     */
    public SelectFile(Project project) {
        super(project);
        this.project = project;
        this.initEvent();
        init();
        setTitle(GlobalDict.TITLE_INFO);
    }

    @Nullable
    @Override
    protected JComponent createCenterPanel() {
        return this.contentPane;
    }

    private void initEvent() {
        // 将当前选中的model设置为基础路径
        VirtualFile path = ProjectUtils.getBaseDir(project);
        // 选择路径
        pathChooseButton.addActionListener(e -> {
            VirtualFile virtualFile = FileChooser.chooseFile(FileChooserDescriptorFactory.createSingleFileDescriptor(), project, path);
            if (virtualFile == null) {
                Messages.showWarningDialog("没有选择到文件！！", GlobalDict.TITLE_INFO);
            } else {
                if (!StrConstant.FILE_SUFFIX_SET.contains(FileUtil.getSuffix(virtualFile.getName()))) {
                    Messages.showWarningDialog("不支持的文件类型！", GlobalDict.TITLE_INFO);
                    return;
                }
                pathField.setText(virtualFile.getPath());
            }
        });

        // 下载模板的路径选择
        chooseDownloadButton.addActionListener(e -> {
            VirtualFile virtualFile = FileChooser.chooseFile(FileChooserDescriptorFactory.createSingleFolderDescriptor(), project, path);
            if (virtualFile != null) {
                String format = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                downloadTemplateField.setText(virtualFile.getPath() + "/template-" + format + ".xlsx");
            } else {
                Messages.showWarningDialog("没有选择到文件夹！", GlobalDict.TITLE_INFO);
            }
        });

        downloadTemplateButton.addActionListener(e -> {
            String downloadTemplateFieldText = downloadTemplateField.getText();
            if (StrUtil.isBlank(downloadTemplateFieldText)) {
                Messages.showWarningDialog("模板下载路径不能为空！", GlobalDict.TITLE_INFO);
                return;
            }
            File ioFile = new File(downloadTemplateFieldText);
            try {
                // 创建文件
                ioFile.createNewFile();
                if (!ioFile.isFile()) {
                    Messages.showWarningDialog("请填写正确的文件路径！", GlobalDict.TITLE_INFO);
                    return;
                }
                InputStream inputStream = SelectFile.class.getResourceAsStream("/template.xlsx");
                FileUtil.writeFromStream(inputStream, ioFile);
                Messages.showInfoMessage("下载模板成功！", GlobalDict.TITLE_INFO);
            } catch (IOException exception) {
                exception.printStackTrace();
                Messages.showWarningDialog("下载模板失败！", GlobalDict.TITLE_INFO);
            }
        });
    }

    @Override
    protected void doOKAction() {
        String selectFilePath = pathField.getText();
        if (StrUtil.isBlank(selectFilePath)) {
            Messages.showWarningDialog("请选择模板文件！", GlobalDict.TITLE_INFO);
            return;
        }
        onOk();
        super.doOKAction();
    }

    /**
     * 确认按钮回调事件
     */
    private void onOk() {
        String selectFilePath = pathField.getText();
        // 针对Linux系统路径做处理
        selectFilePath = selectFilePath.replace("\\", "/");
        // 保存配置
        cacheDataUtils.setSelectFilePath(selectFilePath);
        cacheDataUtils.setTableExistJump(tableExistJumpCheckBox.isSelected());
        // 解析文件，生成sql并执行
        ExcelAnalysisServiceImpl excelAnalysisService = new ExcelAnalysisServiceImpl();
        EasyExcel.read(new File(selectFilePath), excelAnalysisService)
                .headRowNumber(0)
                .doReadAll();
        excelAnalysisService.runSql();
    }

}
